package com.yzt.p_base.utils;

import android.content.Context;
import android.content.res.Resources;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import androidx.annotation.DimenRes;

import com.yzt.p_base.AppUtils;

import java.lang.reflect.Field;

/**
 * author : bob
 * date   : 2022/11/29
 * desc   :
 */
public class DisplayUtils {

    public static int dp2px(float dp) {
        final float scale = AppUtils.getApp().getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    /**
     * 将dip或dp值转换为px值，保证尺寸大小不变
     *
     * @param （DisplayMetrics类中属性density）
     */
    public static int dip2px(float dipValue) {
        final float scale = AppUtils.getApp().getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * 获取屏幕宽；返回int
     */
    public static int getDisplayPxWidth() {
        DisplayMetrics dm = AppUtils.getApp().getResources().getDisplayMetrics();
        return dm.widthPixels;
    }

    public static int getDimensionPixelSize(@DimenRes int id) {
        return AppUtils.getApp().getResources().getDimensionPixelSize(id);
    }

    /**
     * 获取屏幕宽；返回int
     */
    public static int getDisplayPxHeight() {
        DisplayMetrics dm = AppUtils.getApp().getResources().getDisplayMetrics();
        return dm.heightPixels;
    }

    /**
     * 获取状态栏高度px
     */
    public static int getStatusBarHigh(Resources res) {
        int statusBar;
        try {
            Class<?> c;
            c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            statusBar = res.getDimensionPixelSize(x);
        } catch (Exception e) {
            statusBar = 0;
        }
        return statusBar;
    }

    /**
     * 获得屏幕宽度
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }
}
